<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="12"
          ><div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              clearable
              @clear="getUsers"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUsers"
              ></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="6"
          ><div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible = true">用户添加</el-button>
          </div></el-col
        >
      </el-row>

      <el-table :data="userList" style="width: 100%" border striped>
        <el-table-column type="index" label="#"> </el-table-column>

        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template v-slot="slot">
            <el-switch
              v-model="slot.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(slot.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="slot">
            {{ slot.a }}
            <el-button type="primary" icon="el-icon-edit" @click="editUser(slot.row)"></el-button>
            <el-button type="primary" icon="el-icon-delete" @click="removeUser(slot.row.id)"></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button type="primary" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%" 
      @close="closeDialog()"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" type="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="validAddUser"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- edit  -->
    <el-dialog
      title="修改用户"
      :visible.sync="EditdialogVisible"
      width="50%"
      @close="editUserClose()"
      >
      <el-form :model="EditUser" :rules="editRules" ref="EditRuleFormRef" label-width="70px" >
          <el-form-item label="姓名" prop="username">
            <el-input v-model="EditUser.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="EditUser.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="EditUser.mobile"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserValid">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const checkMobile = (rule, value, callback) => {
        let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if(reg.test(value)){
          callback()
        }else{
          callback(new Error('手机号码格式不正确'))
        }

      };
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      userList: [],
      dialogVisible:false,
      EditdialogVisible:false,
      ruleForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      EditUser:{},
      rules:{
        username: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
          ],
        password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
          ],
        email:[
             { required: true, message: '请输入邮箱', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        mobile:[
           { required: true, message: '请输入电话', trigger: 'blur' },
           { validator: checkMobile, trigger: 'blur' }
        ]
      },
      
      editRules:{
        email:[
             { required: true, message: '请输入邮箱', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        mobile:[
           { required: true, message: '请输入电话', trigger: 'blur' },
           { validator: checkMobile, trigger: 'blur' }
        ]
      }

    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUsers();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUsers();
    },

    getUsers() {
      this.$http.get("users", { params: this.queryInfo }).then(
        (req) => {
          //  console.log(req.data)
          if (req.data.meta.status !== 200) return this.$message.error("fail");
          this.total = req.data.data.total;
          this.userList = req.data.data.users;
          //console.log(this.userList)
        },
        (error) => {}
      );
    },
    userStateChanged(userInfo) {
      this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`).then(
        (req) => {
          console.log(req.data);
          if (req.data.meta.status !== 200) {
            req.data.data.mg_state = !req.data.data.mg_state;
            return this.$message.error("fail");
          }
          this.$message.success("success");
        },
        (error) => {
          this.$message.error("fail");
        }
      );
    },
    closeDialog(){
      this.$refs.ruleFormRef.resetFields()
    },
    editUserClose(){
      this.$refs.EditRuleFormRef.resetFields()
    },
    editUser(row){
      this.EditdialogVisible = true
      //console.log(row.id)
      this.$http.get('users/'+ row.id).then(
        (req) =>{
          this.EditUser =req.data.data
          
        },
        (error)=>{

        }
      )
    },
    removeUser(id){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(
          req =>{

            this.$http.delete('users/'+id).then(
              req=>{
                if(req.data.meta.status !== 200)
                  return this.$message.fail('删除失败')
                this.$message.success('删除成功')
                this.getUsers()
              },
              error=>{

              }
            )
            
              
          },

          error =>{
            return this.$message.info('取消删除')
          },
        )
        
    },
    editUserValid(){
      this.$refs.EditRuleFormRef.validate(valid=>{
        if(!valid) return
        this.$http.put('users/'+this.EditUser.id,{email:this.EditUser.email,mobile:this.EditUser.mobile}).then(
          (req)=>{
            if(req.data.meta.status !== 200)
              return this.$message.fail('更新失败')
            this.$message.success('更新成功')
            this.EditdialogVisible = false
            this.getUsers()
          }
        )
      })
    },
    validAddUser(){
      this.$refs.ruleFormRef.validate(valid=>{
        if(!valid) return 

        this.$http.post('users',this.ruleForm).then(
          (req) =>{
            
          if(req.data.meta.status !== 201)
              return this.$message.error('fail')
            this.$message.success('用户添加成功')
            this.dialogVisible=false
            this.getUsers()
          },
          (error) =>{
            this.$message.error('fail')
          }
        )
      })
    }
  },
};
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 100%;
}
</style>